package servlets;

import java.io.IOException;
import java.security.Provider.Service;

import javaPersistence.Client;
import javaPersistence.Producto;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.FormData;

/**
 * Servlet implementation class LoadDataService
 */
@WebServlet("/LoadService")
public class LoadDataService extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoadDataService() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int idService = 0;
		String nameService = "";
		double priceService = 0d;
		String descService = "";
		FormData fdata = new FormData();	
		try {
			HttpSession sess = request.getSession();
			Producto product = new Producto();
			idService = Integer.parseInt(request.getParameter("update"));
			nameService = request.getParameter("nameService");
			priceService = Double.parseDouble(request.getParameter("priceService"));
			descService = request.getParameter("descService");
			if(nameService != null && priceService > 0 && descService != null){
				if(idService == 0){
					if(!product.insertService(nameService, priceService, descService)){
						fdata.setError("Error: Los datos insertados ya existen o estan mal diligenciados.");
					}else{
						fdata.setMsgOK("OK: Los datos fueron almacenados correctamente.");
						fdata.setServices(product.loadAllServices());
					}
				}else{
					if(!product.updateService(idService, nameService, priceService, descService)){
						fdata.setError("Error: Los datos insertados ya existen o estan mal diligenciados.");
					}else{
						fdata.setMsgOK("OK: Los datos fueron actualizados correctamente.");
						fdata.setServices(product.loadAllServices());
					}
				}
			}else{
				fdata.setError("TODOS: Los datos son necesarios");
			}
			sess.setAttribute("FormData", fdata);
			response.sendRedirect(request.getContextPath() + "/jsps/negocio/productos.jsp");
		} catch (Exception e) {
			e.printStackTrace();
			fdata.setError("Error: Los datos insertados ya existen o estan mal diligenciados.");
		}
	}

}
